<!--
  @author:  long
  @date:    2023/3/2
  @file:    客户列表
  @require:
-->
<template>
  <div class="customerList app-container">
    <!-- 客户列表主体 start -->
    <div class="px-2">
      <!-- 搜索 start -->
      <avue-form
        :option="queryFormOption"
        v-model="queryForm"
        ref="queryFormRef"
      >
        <!--   客户状态   -->
        <template #status>
          <el-select
            clearable
            v-model="queryForm.status"
            placeholder="客户状态"
          >
            <!--      过滤掉已转入公海的状态    -->
            <el-option
              v-for="(dict, index) in customer_status.filter(
                item => item.value !== '8'
              )"
              :label="dict.label"
              :value="dict.value"
              :key="index"
            ></el-option>
          </el-select>
        </template>
        <!-- 客户类别 -->
        <template #customerType>
          <el-select
            clearable
            v-model="queryForm.customerType"
            placeholder="客户类别"
          >
            <el-option
              v-for="(dict, index) in customer_class"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </template>
        <!-- 客户星级 -->
        <template #starRating>
          <el-select
            clearable
            v-model="queryForm.starRating"
            placeholder="客户星级"
          >
            <el-option
              v-for="(dict, index) in customer_star"
              :label="dict.label"
              :value="dict.value"
              :key="index"
            ></el-option>
          </el-select>
        </template>
        <!--    更新时间    -->
        <template #updateTime>
          <el-date-picker
            style="width: 100%"
            v-model="updateTime"
            type="daterange"
            start-placeholder="更新时间起"
            end-placeholder="更新时间止"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
          />
        </template>
        <template #menu-form="{}">
          <el-button icon="Search" type="primary" @click="handleQuery"
            >查询
          </el-button>
          <el-button icon="RefreshLeft" @click="handleEmpty">重置</el-button>
          <el-button icon="Filter" link type="primary" @click="openDrawer"
            >高级筛选
          </el-button>
        </template>
      </avue-form>
      <!-- 搜索 end -->

      <!-- 操作按钮 start-->
      <div class="px-2 pb-3 mt-3">
        <el-button type="primary" icon="Plus" @click="addCustomer">
          新建客户
        </el-button>
        <el-button icon="Flag" type="primary" @click="addTask" plain
          >新建任务
        </el-button>
        <!--        <el-button icon="List" type="primary" plain>新建工单</el-button>-->
        <!--        <el-button icon="Refresh" type="primary" plain>转移客户</el-button>-->
        <el-button
          icon="UserFilled"
          type="primary"
          plain
          @click="handleOpenDialog('pool')"
          >转入公海
        </el-button>
        <!--        <el-button icon="Download">导入数据</el-button>-->
        <!--        <el-button icon="Upload">导出数据</el-button>-->
        <el-button icon="EditPen" type="primary" plain @click="toUpdate"
          >编辑客户
        </el-button>
        <el-button icon="Delete" type="primary" plain @click="deleteCustomer"
          >删除客户
        </el-button>
        <el-button
          icon="Upload"
          type="primary"
          plain
          @click="addDialogVisible = true"
          >批量更新
        </el-button>
      </div>
      <!-- 操作按钮 end-->

      <!--   客户列表显示start   -->
      <el-table
        ref="tableRef"
        :data="tableData"
        border
        v-loading="loading"
        style="width: 100%"
        @sort-change="handleSortChange"
        @selection-change="handleSelectionChange"
        @row-dblclick="goDetails"
        @row-click="rowClick"
      >
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column
          label="税号"
          show-overflow-tooltip
          prop="customerTaxcode"
          align="center"
        >
          <!-- <template #default="scope">
                                          <el-button link type="primary" @click="goDetails(scope.row)">{{
                                            scope.row.systemNumber
                                          }}</el-button>
                                        </template> -->
        </el-table-column>
        <el-table-column
          label="客户名称"
          show-overflow-tooltip
          prop="customerName"
        >
          <!-- <template #default="scope">
                                          <el-button link type="primary" @click="goDetails(scope.row)">{{
                                            scope.row.customerName
                                          }}</el-button>
                                        </template> -->
        </el-table-column>
        <el-table-column
          label="客户状态"
          prop="status"
          align="center"
          width="130"
        >
        </el-table-column>
        <el-table-column
          label="归属人员"
          prop="userName"
          align="center"
          width="100"
        >
        </el-table-column>
        <el-table-column label="客户星级" align="center" width="130">
          <template #default="scope">
            <dict-tag :options="customer_star" :value="scope.row.starRating" />
          </template>
        </el-table-column>

        <el-table-column
          label="首联系人"
          width="100"
          prop="mainContactName"
          align="center"
        ></el-table-column>
        <el-table-column
          label="联系电话"
          prop="mainContactPhone"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          label="最后更新时间"
          width="160"
          sortable="custom"
          prop="updateTime"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="170">
          <template #default="scope">
            <el-button
              icon="DocumentChecked"
              size="small"
              plain
              type="primary"
              @click="toOrder(scope.row)"
              >下订
            </el-button>
            <el-button
              icon="CircleCheck"
              size="small"
              plain
              type="warning"
              @click="clickFn(scope.row)"
              >跟进
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryForm.pageNum"
        v-model:limit="queryForm.pageSize"
        @pagination="getList"
      />
      <!--   客户列表显示end   -->

      <!-- 高级筛选 start -->
      <el-drawer class="p-0" size="50%" v-model="drawer">
        <template #header>
          <div class="text-xl font-semibold">高级筛选</div>
        </template>
        <avue-form
          :option="drawerFormOption"
          v-model="queryForm"
          ref="drawerFormRef"
        >
          <template #menu-form="{}">
            <el-button icon="Search" type="primary" @click="handleQuery"
              >查询
            </el-button>
            <el-button icon="RefreshLeft" @click="handleDrawerFormEmpty"
              >重置
            </el-button>
          </template>
          <!--   客户状态   -->
          <template #status>
            <el-select
              v-model="queryForm.status"
              placeholder="客户状态"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(dict, index) in customer_status.filter(
                  item => item.value !== '8'
                )"
                :label="dict.label"
                :value="dict.value"
                :key="index"
              ></el-option>
            </el-select>
          </template>
          <!-- 行业类型 -->
          <template #industryTypeCode>
            <el-select
              v-model="queryForm.industryTypeCode"
              placeholder="行业类别"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(dict, index) in industry_category"
                :key="index"
                :value="dict.value"
                :label="dict.label"
              ></el-option>
            </el-select>
          </template>
          <!-- 客户类别 -->
          <template #customerType>
            <el-select
              v-model="queryForm.customerType"
              placeholder="客户类别"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(dict, index) in customer_class"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </template>
          <!-- 客户星级 -->
          <template #starRating>
            <el-select
              v-model="queryForm.starRating"
              placeholder="客户星级"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(dict, index) in customer_star"
                :label="dict.label"
                :value="dict.value"
                :key="index"
              ></el-option>
            </el-select>
          </template>
          <!-- 客户来源 -->
          <template #origin>
            <el-select
              v-model="queryForm.origin"
              placeholder="客户来源"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(dict, index) in customer_source"
                :label="dict.label"
                :value="dict.value"
                :key="index"
              ></el-option>
            </el-select>
          </template>
          <!--    更新时间    -->
          <template #updateTime>
            <el-date-picker
              style="width: 100%"
              v-model="updateTime"
              type="daterange"
              start-placeholder="更新时间起"
              end-placeholder="更新时间止"
              format="YYYY-MM-DD"
              valueFormat="YYYY-MM-DD"
            />
          </template>
          <!--    归属公司    -->
          <template #orgId>
            <el-tree-select
              style="width: 100%"
              v-model="queryForm.orgId"
              :data="companyOptions"
              clearable
              :props="{
                value: 'id',
                label: 'label',
                children: 'children'
              }"
              placeholder="请选择归属单位"
              value-key="id"
              filterable
            />
          </template>
          <!--    所属部门    -->
          <template #deptId>
            <el-tree-select
              v-model="queryForm.deptId"
              node-key="id"
              style="width: 100%"
              clearable
              class="dept"
              :data="deptData"
              :props="deptProps"
              :render-after-expand="false"
              placeholder="考核部门"
              filterable
            />
          </template>
          <!--    归属人员    -->
          <template #userId>
            <el-select
              v-model="queryForm.userId"
              placeholder="请选择归属人员"
              @focus="userInputFocus"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(item, index) in selectOptionObj['userId']"
                :key="index"
                :label="item.label"
                :value="item.uuid"
              ></el-option>
            </el-select>
          </template>

          <!--    归属企业      -->
          <template #parentId>
            <el-select
              v-model="queryForm.parentId"
              placeholder="请选择所属企业"
              class="w-full"
              filterable
              remote
              :remote-method="queryCustomer"
            >
              <el-option
                v-for="item in parentOptions"
                :key="item.id"
                :label="item.customerName"
                :value="item.id"
              >
                <div>
                  <span>{{ item.customerName }}</span>
                  <span>({{ item.mainContactName }})</span>
                </div>
              </el-option>
            </el-select>
          </template>

          <!-- 行业名称 -->
          <template #hymc>
            <el-select
              v-model="queryForm.hymc"
              placeholder="行业名称"
              class="w-full"
              filterable
              remote
              clearable
              :remote-method="queryHymc"
            >
              <el-option
                v-for="(dict, index) in hymcOptions"
                :key="index"
                :value="dict.hymc"
                :label="dict.hymc"
              ></el-option>
            </el-select>
          </template>
        </avue-form>
      </el-drawer>
      <!-- 高级筛选 end -->
    </div>
    <!-- 客户列表主体end -->
    <!--  公共弹窗start -->
    <el-dialog
      v-model="dialogObj.visible"
      destroy-on-close
      :close-on-click-modal="false"
      :width="dialogObj.width"
      :title="dialogObj.title"
    >
      <!--      新建任务-->
      <!--      <add-task v-if="dialogObj.model == 'task'" />-->
      <!--  转入公海 -->
      <div v-if="dialogObj.model == 'pool'">
        <div class="flex">
          <div class="w-25">备注信息：</div>
          <div>
            <el-input
              v-model="statusDescription"
              rows="5"
              class="mb-2"
              maxlength="100"
              placeholder="输入内容"
              show-word-limit
              type="textarea"
            />
            <div class="text-xs">
              *转移到公海后此客户数据将属于公共资源，原归属人员不能再维护跟进和更新此客户数据。
            </div>
          </div>
        </div>
      </div>

      <!--   底部按钮   -->
      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="dialogSave">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog title="批量更新" v-model="addDialogVisible" width="400px">
      <el-upload
        ref="upload"
        v-loading="upload.isUploading"
        element-loading-text="正在上传模板 请稍候"
        :limit="1"
        action="#"
        :http-request="requestAddUpload"
        accept=".xlsx"
        :disabled="upload.isUploading"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip" style="color: red">
            提示：仅允许导入“xlsx”格式文件！
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="fetchFile()"
              >下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelPL">取 消</el-button>
        </span>
      </template>
    </el-dialog>

    <!--  公共弹窗end -->
    <!--  弹窗选择组件  -->
    <SelectDialog :dialog-param="dialogParam" @ok="selectData"></SelectDialog>
    <!-- 跟进 -->
    <FollowUp :dialogParam="followUpParam" @close="closeFn"></FollowUp>
    <!--   新建任务   -->
    <TaskFrom :dialogParam="taskParam" @closeDialog="closeTask"></TaskFrom>
  </div>
</template>

<script setup name="CustomerList">
import { getCurrentInstance, toRaw } from 'vue'
import AddTask from '@/views/customerManage/modules/addTask.vue'
import { useRouter } from 'vue-router'
import SelectDialog from '@/components/SelectDialog/index.vue'
import FollowUp from '@/businessComponents/FollowUp'
import TaskFrom from '@/views/rsgl/taskManage/modules/add.vue'
import {
  delCustomer,
  getCustomerList,
  importCustomerSsDigital,
  updateForOpenSea,
  getDmGyHyByName
} from '@/api/customerManage/customerList'
import { treeselect, treeselectNoPriv } from '@/api/rsgl/zzjg'
import useUserStore from '@/store/modules/user'
import { getTreeNodeByParam, getUniqueUserId } from '@/utils/commo'
import useCommonStore from '@/store/modules/common'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const router = useRouter()
// 通用数据store
const commonStore = useCommonStore()

const { proxy } = getCurrentInstance()
const drawer = ref(false) //抽屉弹窗
const loading = ref(false)
const data = reactive({
  deptData: [],
  deptProps: { label: 'label' },
  queryForm: {
    pageNum: 1,
    pageSize: 10,
    orgId: userStore.user.orgId == 484 ? '' : userStore.user.orgId,
    userId: '',
    deptId: '' //userStore.user.dept.deptId
  },
  total: 0,
  tableData: [],
  updateTime: [], //更新时间
  // 查询的form表单配置
  queryFormOption: {
    labelWidth: 0,
    menuSpan: 6,
    submitBtn: false,
    emptyBtn: false,
    column: [
      {
        prop: 'customerNameOrNumber',
        placeholder: '客户名称、编号',
        span: 4
      },
      {
        prop: 'status', //客户状态
        span: 3
      },
      {
        prop: 'customerType', //客户类别
        span: 3
      },
      {
        prop: 'starRating', //客户星级
        span: 3
      },
      {
        prop: 'updateTime',
        span: 5
      }
    ]
  },
  //   高级筛选弹窗form表单配置
  drawerFormOption: {
    labelWidth: 80,
    submitBtn: false,
    emptyBtn: false,
    column: [
      {
        label: '客户名称',
        prop: 'customerNameOrNumber',
        placeholder: '客户名称、编号',
        span: 12
      },
      {
        label: '客户状态',
        prop: 'status',
        span: 12
      },
      {
        label: '行业类型',
        prop: 'industryTypeCode',
        placeholder: '行业类型',
        span: 12
      },
      {
        label: '客户类别',
        prop: 'customerType',
        placeholder: '客户类别',
        span: 12
      },
      {
        label: '客户星级',
        prop: 'starRating',
        placeholder: '客户星级',
        span: 12
      },
      {
        label: '客户来源',
        prop: 'origin',
        placeholder: '客户来源',
        span: 12
      },
      {
        label: '联系人',
        prop: 'phoneAndNameContact',
        placeholder: '联系人',
        span: 12
      },
      {
        label: '归属企业',
        prop: 'parentId',
        placeholder: '归属企业',
        span: 12
      },
      {
        label: '归属公司',
        prop: 'orgId',
        placeholder: '归属公司',
        span: 12,
        display: userStore.user.orgId == '484'
      },
      {
        label: '所属部门',
        prop: 'deptId',
        placeholder: '归属公司',
        span: 12
      },
      {
        label: '归属人员',
        prop: 'userId',
        span: 12
      },
      {
        label: '行业名称',
        prop: 'hymc',
        span: 12,
        remote: true,
        filterable: true
      }
    ]
  },
  dialogObj: {
    visible: false,
    title: '',
    width: '50%',
    model: '',
    type: {
      task: { title: '新建任务', width: '40%' },
      pool: { title: '转入公海', width: '40%' }
    }
  },
  selectionData: [],
  dialogParam: {}, //弹窗组件配置
  selectOptionObj: {}, // select
  followUpParam: {}, //跟进
  upload: {
    isUploading: false
  },
  addDialogVisible: false
})
const {
  updateTime,
  queryForm,
  tableData,
  queryFormOption,
  drawerFormOption,
  dialogObj,
  selectionData,
  dialogParam,
  selectOptionObj,
  total,
  upload,
  addDialogVisible,
  followUpParam,
  deptData,
  deptProps
} = toRefs(data)
const {
  customer_status,
  customer_class,
  customer_source,
  customer_star,
  industry_category
} = proxy.useDict(
  'customer_status',
  'customer_class',
  'customer_source',
  'customer_star',
  'industry_category'
)

const companyOptions = ref([])
const parentOptions = ref([])
const statusDescription = ref('') //移入公海状态备注
const taskParam = ref({})
const orderType = ref('0')

/**
 * 获取部门数据查询
 */
const getDeptData = async () => {
  let params = {
    deptId: ''
  }
  treeselect(params).then(res => {
    deptData.value = res.data
    console.info(' deptData.value', deptData.value)
  })
}

/**
 * 排序
 * @param a
 * @param b
 */
function handleSortChange(column, prop, order) {
  // 正序
  if (column.order == 'ascending') {
    orderType.value = '1'
  } else {
    orderType.value = '0'
  }
  handleQuery()
  console.info(column.order)
}

function cancelPL() {
  addDialogVisible.value = false
  proxy.$refs.upload.clearFiles()
}

/** 下载模板操作 */
function fetchFile(index) {
  window.location.href =
    import.meta.env.VITE_VIEW_FILEDOWN_URL +
    '/file/系统模板文件/客户档案更新模板_20240506111636A008.xlsx'
}

// 批量更新
async function requestAddUpload(data) {
  upload.value.isUploading = true
  let formData = new FormData()
  formData.append('file', data.file)
  try {
    const res = await importCustomerSsDigital(formData)
    if (res.code === 200) {
      // console.log(res)
      proxy.$modal.msgSuccess('批量更新成功')
    } else {
      ElMessage({
        showClose: true,
        message: res.msg,
        type: 'error',
        duration: 10000
      })
    }
    upload.value.isUploading = false
    addDialogVisible.value = false
    proxy.$refs.upload.clearFiles()
    await getList()
  } catch (e) {
    console.log(e)
    // proxy.$modal.msgError('上传文件服务异常 请重试')
    upload.value.isUploading = false
  }
}

// 新建任务
const addTask = () => {
  //   taskParam.value.isVisible = true
  //   taskParam.value.businessType = '3'
  let object = {
    businessType: '3'
  }
  router.push({
    path: '/rsgl/other/addTasking',
    query: { taskParam: JSON.stringify(object) }
  })
}
// 任务关闭
const closeTask = () => {
  taskParam.value.isVisible = false
}
/**
 * 下订
 * @param row
 */
const toOrder = row => {
  let obj = {
    customerId: row.id,
    customerName: row.customerName,
    customerType: 'customer'
  }
  router.push({
    path: '/sales/indent/salesOrderForm',
    query: { salesOrderData: JSON.stringify(obj) }
  })
}

/**
 * 跟进
 * @param row
 */
const clickFn = row => {
  // 跟进
  followUpParam.value.isVisible = true
  followUpParam.value.tableName = 'biz_customer'
  followUpParam.value.businessId = row.customerNumber
  followUpParam.value.customer = row.customerName
  followUpParam.value.linkId = row.mainContactId //'联系人id'
  followUpParam.value.linkName = row.mainContactName //'联系人名称'
  followUpParam.value.status = row.statusCode //客户状态
}

// 组件关闭隐藏
const closeFn = row => {
  // 跟进
  followUpParam.value.isVisible = false
  getList()
}

/**
 * 所属企业模糊搜索
 * @param val 当前输入的值
 */
function queryCustomer(val) {
  let params = {
    pageNum: 1,
    pageSize: 10,
    customerNameOrNumber: val
  }
  getCustomerList(params).then(res => {
    parentOptions.value = res.data.records
  })
}

/**
 * 弹窗选取获取选中的值
 * @param val
 *  type 业务类型
 *     selectData 选中的数据[{value: 1, label: '王晓易', $treeNodeId: 2}]
 *     labelData 选中的数据label ['王晓易']
 *     defaultCheckedKeys 选中的数据id [1]
 *     dialogVisible: false 弹出框的关闭
 */
function selectData(val) {
  console.info('val', val)
  //归属人员
  if (val.type == 'userId') {
    if (!val.selectData.length) {
      queryForm.value[val.type] = ''
    } else {
      selectOptionObj.value[val.type] = val.selectData
      queryForm.value[val.type] = val.defaultCheckedKeys[0]
    }
  }
}

/**
 * 根据当前用户回填归属人员表单
 */
async function getDefaultUserInfo(userId, orgId) {
  console.log(userId, orgId, 'userId, orgId')
  let id = ''
  if (userId) {
    id = userId
  } else {
    //获取当前用户id
    id = userStore.user.userId
  }
  if (orgId == 484) {
    queryForm.value.userId = ''
    return
  }
  //获取部门人员数据
  const deptUserData = await commonStore.getUseTreeData({ deptId: orgId })

  //根据当前用户id获取uuid
  let obj = getTreeNodeByParam(deptUserData, id, 'id', [])
  console.info('obj----------', obj)
  selectOptionObj.value.userId = obj
  queryForm.value.userId = obj[0].uuid
}

/**
 * 弹窗保存
 */
function dialogSave() {
  const params = getParamsForDialogSave()
  switch (dialogObj.value.model) {
    case 'pool': //公海
      console.info('公海保存')
      // 移入公海
      updateForOpenSea(params).then(res => {
        proxy.$modal.msgSuccess(res.msg)
        dialogObj.value.visible = false
        getList()
      })
      break
  }
}

function getParamsForDialogSave() {
  if (!selectionData.value.length) {
    proxy.$modal.msgWarning('请选择数据')
    return
  }
  console.info(selectionData.value)
  const array = selectionData.value.map(item => {
    return {
      statusDescription: statusDescription.value,
      id: item.id,
      status: '8',
      userId: '0',
      userName: '-'
    }
  })
  return array
}

/**
 * 归属人员input获取焦点事件
 */
function userInputFocus() {
  dialogParam.value.type = 'userId'
  dialogParam.value.title = '选择归属人员'
  dialogParam.value.dataType = 'person'
  dialogParam.value.multiple = false
  dialogParam.value.checkStrictly = false
  dialogParam.value.nodeKey = 'uuid'
  dialogParam.value.apiParams = { deptId: queryForm.value.orgId }

  selectOptionObj.value['userId'] = []

  // 有默认值
  if (queryForm.value['userId'] && queryForm.value['userId'].length) {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = [queryForm.value['userId']]
  } else {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = []
  }
}

/**
 * 获取归属公司数据
 * @returns {Promise<void>}
 */
async function getCompany() {
  console.log(userStore.user.orgId, 'userStore.user.orgId')
  if (userStore.user.orgId != 484) {
    queryForm.value.orgId = userStore.user.orgId * 1
    // 所属单位列表
    let response = await treeselect({ deptType: 1 })
    companyOptions.value = response.data
  } else {
    //   无权限的所属公司
    let response = await treeselectNoPriv({ deptType: 1 })
    companyOptions.value = response.data
  }
}

/**
 * 获取客户列表
 */
function getList() {
  loading.value = true
  console.info('userStore', updateTime.value)
  let userObj = {
    id: ''
  }
  if (queryForm.value.userId != '' && queryForm.value.userId != null) {
    // 获取查询到的user数据对象
    userObj = getUniqueUserId(
      selectOptionObj.value['userId'],
      queryForm.value.userId
    )
  }

  console.info('queryForm', queryForm.value)

  let params = JSON.parse(JSON.stringify(queryForm.value))
  if (updateTime.value != null && updateTime.value.length > 0) {
    params.updateTimeStart = updateTime.value[0] + ' 00:00:00'
    params.updateTimeEnd = updateTime.value[1] + ' 23:59:59'
  } else {
    params.updateTimeStart = undefined
    params.updateTimeEnd = undefined
  }
  params.userId = userObj.id
  params.orderType = orderType.value
  // params.orgId =  userStore.user.orgId != 484 ? userStore.user.orgId : 484

  delete params.updateTime
  console.info('params', params)
  getCustomerList(params)
    .then(res => {
      if (res.data != null) {
        tableData.value = res.data.records
        total.value = res.data.total
      } else {
        tableData.value = []
        total.value = 0
      }
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 弹窗关闭
 */
function handleCloseDialog() {
  dialogObj.value.visible = false
}

/**
 * 弹窗开启操作
 * @param type 弹窗组件类型
 *
 */
function handleOpenDialog(type) {
  if (type == 'pool') {
    if (!selectionData.value.length) {
      proxy.$modal.msgWarning('请选择要转入的数据')
      return
    }
  }
  statusDescription.value = ''
  dialogObj.value.title = dialogObj.value.type[type].title
  dialogObj.value.width = dialogObj.value.type[type].width
  dialogObj.value.model = type
  dialogObj.value.visible = true
}

/**
 * 表格多选
 */
function handleSelectionChange(val) {
  selectionData.value = val
  console.info('selectionData', selectionData)
}

// 单击行
function rowClick(row, column, event) {
  // 根据id判断当前点击的是否被选中
  const selected = selectionData.value.some(item => item.id === row.id)
  if (!selected) {
    // 选择
    selectionData.value.push(row)
    proxy.$refs.tableRef.toggleRowSelection(row, true)
  } else {
    // 取消
    var finalArr = selectionData.value.filter(item => {
      return item.id !== row.id
    })
    // 取消后剩余选中的
    selectionData.value = finalArr
    proxy.$refs.tableRef.toggleRowSelection(row, false)
  }
}

/**
 * 新建客户
 */
function addCustomer() {
  router.push({
    path: '/customerManage/customerModules/customerAdd',
    query: { flag: 'add' }
  })
}

/**
 * 查询
 */
function handleQuery() {
  queryForm.value.pageNum = 1
  getList()
}

/**
 * 客户编辑
 */
function toUpdate() {
  if (!selectionData.value.length) {
    proxy.$modal.msgWarning('请选择要编辑的数据')
    return
  }
  if (selectionData.value.length > 1) {
    proxy.$modal.msgWarning('只能编辑一条数据')
    return
  }
  router.push({
    path: '/customerManage/customerModules/customerEdit',
    query: { flag: 'update', customerId: selectionData.value[0].id }
  })
}

/**
 * 跳转详情
 * @param row 行数据
 */
function goDetails(row) {
  router.push({
    path: '/customerManage/customerModules/customerDetails',
    query: { customerId: row.id }
  })
}

/**
 * 删除客户
 */
function deleteCustomer() {
  if (!selectionData.value.length) {
    proxy.$modal.msgWarning('请选择要删除的数据')
    return
  }
  proxy.$modal
    .confirm('是否确认删除选中的客户数据-？')
    .then(res => {
      let ids = selectionData.value
        .map(item => {
          return item.id
        })
        .join(',')
      console.info('ids', ids)
      const params = {
        ids
      }
      delCustomer(params).then(res => {
        proxy.$modal.msgSuccess(res.msg)
        getList()
      })
    })
    .catch(() => {})
}

/**
 * 初始化
 */
async function init() {
  await getDefaultUserInfo(userStore.user.userId, userStore.user.orgId)
  // 获取归属公司数据
  getCompany()
  // 获取所属部门数据
  getDeptData()

  queryForm.value.userId = ''
  handleQuery()
}

init()

/**
 * 打开高级筛选抽屉
 */
function openDrawer() {
  drawer.value = true
}

/**
 * 重置
 */
async function handleEmpty() {
  updateTime.value = []
  proxy.$refs.queryFormRef.resetFields()
  queryForm.value = {
    pageNum: 1,
    pageSize: 10,
    customerNameOrNumber: '',
    phoneAndNameContact: '',
    orgId: userStore.user.orgId == 484 ? '' : userStore.user.orgId,
    customerType: '',
    starRating: '',
    status: '',
    deptId: userStore.user.orgId == 484 ? '' : userStore.user.dept.deptId
  }
  await getDefaultUserInfo(userStore.user.userId, userStore.user.orgId)

  await getList()
}

/**
 * 高级筛选清空
 * @returns {Promise<void>}
 */
async function handleDrawerFormEmpty() {
  updateTime.value = []
  // proxy.$refs.drawerFormRef.resetFields()

  queryForm.value = {
    parentId: '',
    origin: '',
    industryTypeCode: '',
    customerNameOrNumber: '',
    phoneAndNameContact: '',
    pageNum: 1,
    pageSize: 10,
    orgId: userStore.user.orgId == 484 ? '' : userStore.user.orgId,
    customerType: '',
    starRating: '',
    status: '',
    deptId: userStore.user.orgId == 484 ? '' : userStore.user.dept.deptId
  }
  console.info('queryForm.value', queryForm.value)

  await getDefaultUserInfo(userStore.user.userId, userStore.user.orgId)
  // if (userStore.user.orgId != '484') {
  //   queryForm.value.orgId = userStore.user.orgId * 1
  // }
  await getList()
}
// 行业名称检索
const hymcOptions = ref([])
const queryHymc = async val => {
  let res = await getDmGyHyByName({ hymc: val, pageSize: 30 })
  console.log('res===>', res)
  hymcOptions.value = res.data
}
</script>

<style scoped lang="scss">
.customerList {
  .el-drawer .avue-form {
    @apply p-0;
  }
}
</style>
